var watson = require('watson-developer-cloud');
var http = require('http');
var fs = require('fs');
module.exports = function(RED) {
	function ArcherVisualRecognition(config) {
		RED.nodes.createNode(this, config);
		var node = this;
		this.on('input', function(msg) {
			var imageUrl = msg.payload.picUrl;
			var visual_recognition = watson.visual_recognition({
				//url: "https://gateway.watsonplatform.net/visual-recognition-beta/api",
				password: "37GVMfCJSxbU",
				username: "8e8b5dc0-2b07-4955-89d2-b4aac8477ae3",
				version: 'v2-beta',
				version_date: '2015-12-02'
			});

			var identifiers = "";
			var sortedResult;
			
			console.log(__dirname);
			console.log(__filename);
			//var watsonJson=fs.readFileSync(__dirname+'/watson6.json');
			var watsonJson=fs.readFileSync('./nodes/archerVisualRecognition/watson6.json');
			http.get(imageUrl, function(res) {

				var params = {
					images_file: res,
					classifier_ids:watsonJson
				}
				visual_recognition.classify(params, function(err, result) {
					if (err) {
						console.log(err);
					} else {

						identifiers = result;
						sortedResult = result.images[0].scores;
						sortedResult.sort(function(a, b) {
							return b.score - a.score;
						})
					}
					console.log(sortedResult);
					msg.payload.result = sortedResult;
					node.send(msg);
				});

			});
		});
	}

	RED.nodes.registerType("archer-visual-recognition", ArcherVisualRecognition);
}